package com.lee.filter;

import com.lee.customize.CustomizeHttpServletRequest;
import com.lee.customize.CustomizeSession;
import com.lee.customize.CustomizeSessionContainer;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.HttpCookie;

public class CustomizeSessionFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CustomizeSessionFilter init");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        CustomizeHttpServletRequest request = new CustomizeHttpServletRequest((HttpServletRequest) req, (HttpServletResponse) resp);
        chain.doFilter(request, resp);

        // 这里不能设置cookie，因为reponse此时已经提交了
        /*CustomizeSession session = (CustomizeSession) request.getCustomizeSession();
        if (session != null && session.getIsNew()) {
            HttpServletResponse response = (HttpServletResponse) resp;
            Cookie cookie = new Cookie(CustomizeSessionContainer.DEFAULT_SESSION_ID_NAME,
                    session.getId());
            response.addCookie(cookie);
        }*/
    }

    public void destroy() {
        System.out.println("CustomizeSessionFilter destroy");
    }
}
